package com.xiake.zojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.xiake.zojcodesandbox.enums.ExecuteStatusEnum;
import com.xiake.zojcodesandbox.enums.ExitStatusEnum;
import com.xiake.zojcodesandbox.model.ExecuteCodeRequest;
import com.xiake.zojcodesandbox.model.ExecuteCodeResponse;
import com.xiake.zojcodesandbox.model.ExecuteMessage;
import com.xiake.zojcodesandbox.model.JudgeInfo;
import com.xiake.zojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 代码沙箱模板实现
 */
@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long Max_Execute_Time = 5000;
    private static final long Max_Memory = 256;
    private static final String Max_Memory_Param = "-Xmx" + Max_Memory + "m";


    @Override
    public  ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest){
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();


        //1.把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);


        //2.编译文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(compileFileExecuteMessage);
        if(compileFileExecuteMessage.getExitValue()!=0){
            System.out.println("编译失败，无需执行后续流程，直接返回");
            ///删除代码目录
            boolean deleteResult = deleteCode(userCodeFile);
            if (!deleteResult) {
                log.error("deleteCode error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
            }

            //编译失败，直接返回
            return ExecuteCodeResponse.builder()
                    .status(ExecuteStatusEnum.COMPILE_ERROR.getStatus())
                    .message(ExecuteStatusEnum.COMPILE_ERROR.getMessage())
                    .build();
        }

        //3.执行文件
        List<ExecuteMessage> executeMessageList = runCode(userCodeFile,inputList);
        if(executeMessageList.isEmpty()){
            log.error("执行失败，没有返回结果");
            return ExecuteCodeResponse.builder()
                    .status(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getStatus())
                    .message(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getMessage())
                    .build();
        }

        //4.整理输出结果
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(executeMessageList);

        //5.删除用户代码目录
        boolean deleteResult = deleteCode(userCodeFile);
        if (!deleteResult) {
            log.error("deleteCode error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
        }

        return  executeCodeResponse;
    }

    /**
     * 保存用户代码为本地文件
     * @param code
     * @return
     */
    public File saveCodeToFile(String code){
        //"user.dir" 是Java系统属性中的一个键。这个属性表示Java应用程序的“用户工作目录”的路径。
        String userDir = System.getProperty("user.dir");  //获取当前工作目录
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断文件夹是否存在
        if(!FileUtil.exist(globalCodePathName)){
            //不存在则创建
            FileUtil.mkdir(globalCodePathName);
        }
        //每次生成的目录都是不同的，用户代码隔离
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        //读取用户的代码内容写到指定的Main.java文件中
        File userCodeFile=FileUtil.writeString(code, userCodePath, "utf-8");
        return userCodeFile;
    }

    /**
     * 编译代码
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile){
        //编译命令：javac Main.java
        String compileCmd=String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        System.out.println(userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            //退出值不为0，表示编译失败,就不需要执行后续操作了，直接删除用户代码目录，然后返回
            if(executeMessage.getExitValue()!=0){
             log.error("编译失败");
            }
            System.out.println(executeMessage);
            return executeMessage;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    /**
     * 执行代码
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runCode(File userCodeFile,List<String> inputList){
        ArrayList<ExecuteMessage> executeMessageList= new ArrayList<>();
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        for(String input:inputList) {
            //执行命令：java Main 1 2
            String executeCmd = String.format("java %s -Dfile.encoding=UTF-8 -cp %s Main %s",Max_Memory_Param, userCodeParentPath,input);
            try {
                Process runProcess = Runtime.getRuntime().exec(executeCmd);

                //设置守护线程，当主线程执行时间超过设置的最大执行时间，就销毁主线程
                //防止主线程一直占用资源
                //todo 待优化
                new Thread(() -> {
                    try {
                        Thread.sleep(Max_Execute_Time);
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException( e);
                    }
                }).start();

                //返回执行信息
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "执行");
                if(executeMessage.getExitValue()!=0){
                    return  new ArrayList<>();
                }
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);

            } catch (Exception e) {
                throw new RuntimeException("执行错误",e);

            }
        }
        return executeMessageList;
    }

    /**
     * 获取执行结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList){
        long maxTime=0;
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        //将executeMessageList中的每一个ExecuteMessage对象转换为其getMessage方法的返回值，并将这些返回值收集到一个新的列表中。
        List<String> outPutMeassageList =new ArrayList<>();
        //对执行信息列表进行遍历，将每个执行信息对象中的message属性值取出来，并放入到新的列表中。
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(executeMessage.getErrorMessage())){
                //如果执行信息对象中的errorMessage属性值不为空，则说明执行失败了
                //用户提交的代码错误
                executeCodeResponse.setMessage(ExecuteStatusEnum.USER_CODE_ERROR.getMessage());
                executeCodeResponse.setStatus(ExecuteStatusEnum.USER_CODE_ERROR.getStatus());
                break;
            }
            outPutMeassageList.add(executeMessage.getMessage());
            //找出最大执行时间
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        executeCodeResponse.setOutputList(outPutMeassageList);
        if(executeMessageList.size()==outPutMeassageList.size()){
            //如果执行信息列表和输出结果列表的长度相同，说明每一条都执行成功
            executeCodeResponse.setStatus(ExecuteStatusEnum.SUCCESS.getStatus());
        }
        //设置JudgeInfo对象
        JudgeInfo judgeInfo = new JudgeInfo();
        // 取用时最大值，便于判断是否超时

        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();

        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 删除用户代码目录
     * @param userCodeFile
     * @return
     */
    public boolean deleteCode(File userCodeFile){

        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeFile.getParentFile().getAbsolutePath());
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }


    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getStatus());
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

}
